import { createRouter, createWebHashHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '@/views/LoginView.vue';
import RegisterView from '@/views/RegisterView.vue';
import FindPwdView from '@/views/FindPwdView.vue';
import PublishBookView from '@/views/PublishBookView.vue';

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { guestOnly: true }, // 标记只允许未登录用户访问
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: { guestOnly: true }, // 标记只允许未登录用户访问
  },

  {
    path: '/findPwd',
    name: 'findPwd',
    component: FindPwdView,
    meta: { guestOnly: true }, // 标记只允许未登录用户访问
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }, // 标记需要认证
  },
  {
    path: '/book',
    name: 'book',
    component: () => import('../views/BookView.vue'),
    meta: { requiresAuth: true }, // 标记需要认证
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/UserView.vue'),
    meta: { requiresAuth: true }, // 标记需要认证
  },
  {
    path: '/order/:transactionId?/:ownerId?/:type?',
    name: 'order',
    component: () => import('../views/OrderView.vue'),
    meta: { requiresAuth: true }, // 标记需要认证
  },
  {
    path: '/comment/:commentId?',
    name: 'comment',
    component: () => import('../views/CommentView.vue'),
    meta: { requiresAuth: true }, // 标记需要认证
  },
  {
    path: '/person',
    name: 'person',
    component: () => import('../views/PersonView.vue'),
    meta: { requiresAuth: true }, // 标记需要认证
  },
  {
    path: '/publish-book/:ownerId?/:type?',
    name: 'publishBook',
    component: PublishBookView, // 直接指向新页面组件
    meta: { requiresAuth: true }, // 标记需要认证
  },
];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
});

// 导航守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('kuaikuai'); // 假设 token 存储在 localStorage 中
  const isGuestRoute = to.matched.some(record => record.meta.guestOnly);
  const isProtectedRoute = to.matched.some(record => record.meta.requiresAuth);

  if (isGuestRoute && isAuthenticated) {
    // 如果用户已登录且尝试访问仅限未登录用户的页面（如登录页）
    next({ path: '/' }); // 重定向到主页
  } else if (isProtectedRoute && !isAuthenticated) {
    // 如果用户未登录且尝试访问需要认证的页面
    next({ path: '/login' }); // 重定向到登录页
  } else {
    // 否则继续导航
    next();
  }
});

export default router;